package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-admin/cache"
	"post-admin/models"
	"post-admin/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	redis_key := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if pkg.Md5Str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}
	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var post []models.Post
	redis_key := "post_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Preload("User").Offset(offset).Limit(size).Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &post)
	}

	var total int64
	models.DB.Model(&models.Post{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "查询成功",
		"data":  post,
		"total": total,
	})
	return
}

func Collection(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	postId, _ := strconv.Atoi(c.Query("post_id"))
	var collection models.Collection
	err := models.DB.Where("user_id=? and post_id=?", userId, postId).First(&collection).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复收藏",
		})
		return
	}
	collection = models.Collection{
		UserId: userId,
		PostId: postId,
	}
	err = models.DB.Create(&collection).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	var post models.Post
	err = models.DB.Where("id=?", postId).First(&post).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不存在",
		})
		return
	}
	post.CollectionCount++
	err = models.DB.Save(&post).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏数量添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "收藏成功",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	redis_key := "post_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &post)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查看成功",
		"data": post,
	})
	return
}
